import uuid

from marshmallow import fields, validate
from sqlalchemy import CHAR, VARCHAR, DateTime

from config.database import db
from config.marshmallow_config import ma


class Company(db.Model):
    __tablename__ = 'company'

    id = db.Column(CHAR(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = db.Column(VARCHAR(50), nullable=False)
    address = db.Column(VARCHAR(100), nullable=False)
    phone = db.Column(VARCHAR(12), nullable=False)
    mobile = db.Column(VARCHAR(11), nullable=True)
    contact = db.Column(VARCHAR(20), nullable=False)
    created_at = db.Column(DateTime, nullable=True)
    created_user_id = db.Column(CHAR(36), nullable=True)
    updated_at = db.Column(DateTime, nullable=True)
    updated_user_id = db.Column(CHAR(36), nullable=True)
    pic = db.Column(CHAR(36), nullable=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'address': self.address,
            'phone': self.phone,
            'mobile': self.mobile,
            'contact': self.contact,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
            'created_user_id': self.created_user_id,
            'updated_user_id': self.updated_user_id,
            'pic': self.pic
        }


class CompanySchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Company
        load_instance = True

    name = fields.String(required=True, validate=validate.Length(min=1, max=50))
    address = fields.String(required=True, validate=validate.Length(max=100))
    phone = fields.String(required=True, validate=validate.Length(max=12))
    mobile = fields.String(validate=validate.Length(max=11))
    contact = fields.String(required=True, validate=validate.Length(max=20))


company_schema = CompanySchema()
companies_schema = CompanySchema(many=True)
